<?php
/**
 * Created by PhpStorm.
 * User: wuchunyin
 * Date: 2018/5/21
 * Time: 19:05
 */


namespace app\index\controller;
use app\index\base_controller\BaseController;
use think\Controller;
use think\Db;
use think\Exception;
use think\facade\Session;

class Role extends BaseController{

    public function roleList(){
        return $this->fetch('role_list');
    }

    public function edit(){
        $id = input()['id'];
        $condition['ROLE_ID'] = $id;
        $data = Db::table('MNG_GZ_ROLE')
            ->where($condition)
            ->find();

        if(empty($data)){
            return '查询角色信息失败';
        }
        $this->assign('data',$data);

        // 权限列表
        $rules = $data['RULES'];
        $ruleList =  $this->getMenuListForEdit($rules);

        $this->assign('ruleList',$ruleList);
        $actions = $data['ACTIONS'];
        $actionList = $this->getActionList($actions);
        $this->assign('actionList',$actionList);
        return $this->fetch('role_edit');
    }

    public function getMenuListForEdit($rules){
        $rulesArr = explode(',',$rules);

        $list = Db::table('MNG_GZ_PAGE')
            ->field(['PAGE_ID'=>'ID','PAGE_NAME'=>'TEXT'])
            ->where(['GROUP_ID'=>'0'])
            ->order('ID asc')
            ->select();

        foreach ($list as $key1=>$menu1){

            $list2 = Db::table('MNG_GZ_PAGE')
                ->field(['PAGE_ID'=>'ID','PAGE_NAME'=>'TEXT'])
                ->where(['GROUP_ID'=>$menu1['ID']])
                ->order(['ID'=>'asc'])
                ->select();

            $list3 = array();
            $list4 = array();
            foreach($list2 as $key2=>$menu2) {
                if ( in_array($menu2['ID'],$rulesArr) ) {
                    $list2[$key2]['selected'] = true;
                }

//                if($menu2['IS_MENU'] == '1') {
                    $list2[$key2]['icon'] = "glyphicon glyphicon-th-list";
                    $list3[] = $list2[$key2];
//                } else {
//                    $list2[$key2]['icon'] = "glyphicon glyphicon-hand-up";
//                    $list4[] = $list2[$key2];
//                }
            }

            $list[$key1]['children1'] = $list3;
            $list[$key1]['children2'] = $list4;
            $list[$key1]['icon'] = "glyphicon glyphicon-home";
            if(in_array($menu1['ID'],$rulesArr)){
                $list[$key1]['selected'] = true;
            }
        }
        return $list;
    }

    public function getActionList($actions){
        $actionArr = explode(',',$actions);

        $list = Db::table('MNG_GZ_ACTION')
            ->where(['IS_BASE'=>'0'])
            ->select();

        $actionList = [];
        foreach ($list as $a){
            $data['ID'] = $a['ACTION_ID'];
            $data['ACTION'] = $a['ACTION'];
            if(in_array($data['ID'],$actionArr)){
                $data['SELECTED'] = true;
            }
            else{
                $data['SELECTED'] = false;
            }
            $actionList[$a['CONTROLLER']][] = $data;
        }
        return $actionList;
    }

    public function add(){
        $ruleList =  $this->getMenuListForEdit("");
        $this->assign('ruleList',$ruleList);
        return $this->fetch('role_add');
    }

    public function addRole(){
        $rules = input('RULES/a');
        if(!empty($rules) && is_array($rules)){
            $data['RULES'] = implode(',',$rules);
        }
        else{
            $data['RULES'] = '';
        }
        $roleId = input('ROLE_ID');
        if (strlen($roleId)!=3) {
            return json_encode(['code'=>'0','msg'=>'角色ID由三位字母或数字组成']);
        }

        $data['ROLE_ID'] = $roleId;
        $data['NAME'] = input('NAME');
        $data['REMARKS'] = input('REMARKS');
        $data['STATUS'] = '1';
        $data['IS_DEL'] = '0';
        $data['UPDATED_TIME'] = time();
        $data['UPDATED_BY'] = Session::get('assUserId');
        $data['CREATED_TIME'] = time();
        $data['CREATED_BY'] = Session::get('assUserId');
        try{
            Db::table('MNG_GZ_ROLE')->insert($data);
            return json_encode(['code'=>'200','msg'=>'新增成功']);
        }
        catch (Exception $e){
            return json_encode(['code'=>'0','msg'=>$e->getMessage()]);
        }
    }

    public function getRoleList(){

        try{
            $limit = input('limit');
            $offset = input('offset');
            $search = input('search');
            $sort = input('sort');
            $order = input('order');
            $sortStr = "$sort $order";
            if(empty($sort)){
                $sortStr = 'ROLE_ID asc';
            }

            if (!empty($search)) {
                $condition[] = ['NAME|REMARKS','like',"%$search%"];
            }
            $condition['IS_DEL'] = '0';

            $list = Db::view('MNG_GZ_ROLE', '*')
                ->limit($offset, $limit)
                ->where($condition)
                ->order($sortStr)
                ->select();

            $total = Db::view('MNG_GZ_ROLE', '*')
                ->where($condition)
                ->count();

            $data['rows'] = $list;
            $data['total'] = $total;
            return $data;
        }
        catch (Exception $e){
            return $e->getMessage();
        }

    }

    public function editRole() {
        $id = input('ROLE_ID');
        $status = input('STATUS');
        $rules = input('RULES/a');
        if(!empty($rules) && is_array($rules)){
            $data['RULES'] = implode(',',$rules);
        }
        else{
            $data['RULES'] = null;
        }
        $actions = input('ACTIONS/a');
        if(!empty($actions) && is_array($actions)){
            $data['ACTIONS'] = implode(',',$actions);
        }
        else{
            $data['ACTIONS'] = null;
        }
        $data['NAME'] = input('NAME');
        $data['REMARKS'] = input('REMARKS');
        if($status === '0' || $status === '1'){
            $data['STATUS'] = input('STATUS');
        }
        $data['UPDATED_TIME'] = time();
        $data['UPDATED_BY'] = Session::get('assUserId');
        try{
            Db::table('MNG_GZ_ROLE')->where(['ROLE_ID'=>$id])->update($data);
            return json_encode(['code'=>'200','msg'=>'修改成功']);
        }
        catch (Exception $e){
            return json_encode(['code'=>'0','msg'=>$e->getMessage()]);
        }
    }

    public function delete(){
        $id = input('id');
        $data['IS_DEL'] = '1';
        $data['UPDATED_TIME'] = time();
        $data['UPDATED_BY'] = Session::get('assUserId');
        $role = Db::table('MNG_GZ_ROLE')
            ->where(['ROLE_ID'=>$id])
            ->find();
        if($role['BASE'] == 1){
            return json_encode(['code'=>'0','msg'=>'基础角色不可删除']);
        }

        try{
            Db::table('MNG_GZ_ROLE')->where(['ROLE_ID'=>$id])->update($data);
            return json_encode(['code'=>'200','msg'=>'删除成功']);
        }
        catch (Exception $e){
            return json_encode(['code'=>'0','msg'=>$e->getMessage()]);
        }
    }

}